package cn.zhx.xa.bi.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ExcelUtils {
    /**
     * excel 转 csv
     *
     * @param multipartFile
     * @return
     */
    public static String excelToCsv(MultipartFile multipartFile) {
        // 读取数据
        List<Map<Integer, String>> list = null;

        // list(0) = (key(列数)，value(值)) {0,日期} {1,用户数}
        // list(1) = (key，value) {0,1} {1,40}

        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            log.error("文件读取失败", e);
        }

        if(CollectionUtil.isEmpty(list)){
            return "";
        }

        //转换为csv
        StringBuilder stringBuilder = new StringBuilder();
        //获取表头 转换成LinkedHashMap
        LinkedHashMap<Integer,String> headerMap = (LinkedHashMap<Integer, String>) list.get(0);
        //过滤空值
        List<String> headerList = headerMap.values().stream().filter(ObjectUtil::isNotEmpty).toList();
        //拼接表头
        stringBuilder.append(StrUtil.join(",",headerList)).append("\n");

        //读取数据
        for (int i = 1; i < list.size(); i++) {
            LinkedHashMap<Integer, String> map = (LinkedHashMap<Integer, String>) list.get(i);
            //过滤空值
            List<String> valueList = map.values().stream().filter(ObjectUtil::isNotEmpty).toList();
            stringBuilder.append(StrUtil.join(",",valueList)).append("\n");
        }
        log.info("转换后的信息:\n"+stringBuilder);
        return stringBuilder.toString();
    }

}